package com.example.demo.service;

import com.example.demo.entity.MonitorcodeInfo;
import com.example.demo.entity.MonitorobjInfo;
import com.example.demo.mapper.MonitorcodeInfoMapper;
import com.example.demo.mapper.MonitorobjInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 测试结果处理类
 * Created by tanjun on 2022-01-09.
 */
@Component
public class AccessTestResultHandler {

    @Autowired
    MonitorobjInfoMapper monitorobjInfoMapper;

    @Autowired
    MonitorcodeInfoMapper monitorcodeInfoMapper;

    //测试连通性成功的处理方法
    public void handlerAccessTestSuccess(String monitorobjId,String monitorcodeId){
        //更新上次成功连接时间
        MonitorobjInfo monitorobjInfo=new MonitorobjInfo();
        monitorobjInfo.setMonitorobjId(monitorobjId);
        monitorobjInfo.setLastaccessTime(new Date());
        monitorobjInfo.setMonitorobjStatus("success");
        monitorobjInfoMapper.updateByPrimaryKeySelective(monitorobjInfo);

        updateLastexecutetime(monitorcodeId,monitorobjInfo.getLastaccessTime());
    }

    //测试连通性失败的处理方法
    public void handlerAccessTestfailure(String monitorobjId,String monitorcodeId){
        //就不更新code表代码的上次成功执行时间了。而是去判断上次成功执行时间，是否超过预警时限，
        // 如果超过了，就变更状态并且发送短信
        MonitorcodeInfo monitorcodeInfo= monitorcodeInfoMapper.selectByPrimaryKey(monitorcodeId);
        //超过30分钟就预警
        if(new Date().getTime()- monitorcodeInfo.getLastexecutetime().getTime()>=1000*60*30){
            MonitorobjInfo monitorobjInfo=new MonitorobjInfo();
            monitorobjInfo.setMonitorobjId(monitorobjId);
            monitorobjInfo.setLastaccessTime(new Date());
            monitorobjInfo.setMonitorobjStatus("fail");
            monitorobjInfoMapper.updateByPrimaryKeySelective(monitorobjInfo);
            //这里添加通知工具，短信或者邮件工具，组织信息，发送出去
            //todo...
        }
    }

    //更新上次执行时间
    private void updateLastexecutetime(String monitorcodeId,Date time){
        //更新上次执行时间
        MonitorcodeInfo monitorcodeInfo=new MonitorcodeInfo();
        monitorcodeInfo.setMonitorcodeId(monitorcodeId);
        monitorcodeInfo.setLastexecutetime(time);
        monitorcodeInfoMapper.updateByPrimaryKeySelective(monitorcodeInfo);
    }
}
